<?php

namespace App\Http\Services\Api\V1\App\Customer;

use App\Http\Controllers\Api\V1\App\Customers\ThirdPartyLoginController;
use App\Models\Customers\Customer;
use App\Models\Extension\Extension;
use App\Models\Setting;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ImageHelper;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Service\AlipayOpenPlatform\AopFactory;
use Tymon\JWTAuth\JWT;
use Tymon\JWTAuth\JWTGuard;

class ThirdPartyService
{
    use ApiChecker;
    /**
     * @param $store_id
     * @param $flag
     * @return Collection
     */
    public function getThirdPartySetting($store_id, $flag)
    {
        /** @var Collection $socialite_extension */
        $socialite_extension = (new Extension)->where('type', 'oauth')
            ->where('code', 'like', '%'.$flag)
            ->get();

        $socialite_login_setting = $socialite_extension->filter(function(Extension $extension) use($store_id){
            $settings = $this->getSocialiteLoginByType($store_id, $extension->type, $extension->code);
            $status = $this->getSocialiteLoginValue($settings, $extension->type, $extension->code, Setting::SETTING_STATUS);

            if ($status) {
                $icon = $this->getSocialiteLoginValue($settings, $extension->type, $extension->code, Setting::SETTING_SOCIALITE_ICON);
                $extension->status = $status;
                $extension->icon = ImageHelper::generateImagePath($icon);
                $extension->app_id = $this->getSocialiteLoginValue($settings, $extension->type, $extension->code, Setting::SETTING_SOCIALITE_APP_ID);
                $extension->sort_order = $this->getSocialiteLoginValue($settings, $extension->type, $extension->code, Setting::SETTING_SOCIALITE_SORT_ORDER);
            }

            return $status;
        })->sortBy('sort_order')
            ->values();

        return $socialite_login_setting;
    }

    /**
     * @return mixed
     * @throws \Exception
     */
    public function handleAlipayCallback()
    {
        $oauthUser = (new AliPayService)->getOauthUser();
        $oauth_type = AliPayService::OAUTH_TYPE_ALIPAY_APP;

        $user = $this->generateUser($oauthUser, $oauth_type);

        return $user;
    }

    /**
     * @param \Illuminate\Database\Eloquent\Model $oauthUser
     * @param $oauth_type
     * @return Customer|array|\Illuminate\Database\Eloquent\Model|null|object
     * @throws \Exception
     */
    public function generateUser($oauthUser, $oauth_type)
    {
        $customer_id = (int) $oauthUser->customer_id;

        if ($customer_id) {
            $customer = $this->loginByCustomerId($customer_id);

        } else {
            $customer = [
                'type'          => $oauth_type,
                'oauth_user_id' => $oauthUser->getKey(),
            ];
        }

        return $customer;
    }

    /**
     * @param $customer_id
     * @return Customer|\Illuminate\Database\Eloquent\Model|null|object
     * @throws \Exception
     */
    private function loginByCustomerId($customer_id)
    {
        $customer = Customer::getCustomer($customer_id);
            $this->checkItemExist($customer);

        /** @var JWTGuard|JWT $jwt */
        $jwt = Auth::guard(Customer::GUARD_NAME);
        $token = $jwt->tokenById($customer_id);

        $customer->update(['jwt_token' => $token]);

        return $customer;
    }

    /**
     * @param $store_id
     * @param $extension_type
     * @param $extension_code
     * @return mixed
     */
    private function getSocialiteLoginByType($store_id, $extension_type, $extension_code)
    {
        $settings = (new Setting)->where('code', $extension_type.'_'.$extension_code)
            ->where('store_id', $store_id)
            ->get();

        return $settings;
    }

    /**
     * @param Collection $settings
     * @param $extension_type
     * @param $extension_code
     * @param $flag
     * @return mixed|null|string
     */
    private function getSocialiteLoginValue(Collection $settings, $extension_type, $extension_code, $flag)
    {
        $status = $settings->where('key', $extension_type.'_'.$extension_code.$flag)
                ->first()
                ->value ?? null;

        return $status;
    }
}